<?php

namespace App\Http\Controllers\Backend\Auth;

use App\Http\Controllers\Backend\BaseController;
use App\Repository\Models\User;
use App\Repository\Repositories\Interfaces\MenuRepository;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Repository\Repositories\Interfaces\AdminUserRepository;
use Tymon\JWTAuth\Facades\JWTFactory;
use Tymon\JWTAuth\JWTAuth;


/**
 * 登录认证控制器
 *
 * @package App\Http\Controllers\Auth
 */
class AuthController extends BaseController
{
    /**
     * 设置成功登录后转向的页面:
     *
     * @var string
     */
    public $redirectPath = '/backend/index';

    /**
     * 设置登录失败后转向的页面
     *
     * @var string
     */
    protected $loginPath = '/backend/auth/login';

    /**
     * 设置退出登录后转向的页面
     *
     * @var string
     */
    protected $redirectAfterLogout = '/backend/auth/login';


    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function postLogin(Request $request,AdminUserRepository $userRepository, MenuRepository $menuRepository)
    {
        $this->validate($request, [
            'email' => 'required',
            'password' => 'required',
        ], [
            'email.required'    => '请输入用户邮箱',
            'password.required' => '请输入用户密码',
        ]);
        
        $user = $userRepository->skipPresenter(1)->with(['roles'])->findWhere($request->only('email'))->first();
        if(!$user){
            return $this->error('用户不存在');
        }
        if($request->input('password') == Crypt::decrypt($user->password)){
            $customClaims =  ['iss' => JWTFactory::iss(), 'iat' => JWTFactory::iat(), 'exp' => JWTFactory::exp(),
                'nbf' => JWTFactory::nbf(), 'sub' => $user->id, 'jti' => \Illuminate\Support\Str::random(),'scope' => 'backend'];
             $payload = JWTFactory::make($customClaims);
             $token = \JWTAuth::encode($payload)->get();
            return $this->success('ok',['user' => $user,'token' => $token]);
        }else{
            return $this->error('账号验证失败');
        }
    }
  
}
